/**
 * Desenvolvido pela Fábrica de Software do CESUPA.
 * Todos os direitos reservados.
 */
package br.cesupa.fabsoft.nomedoprojeto.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Filter used to check if the session contains a authenticated user. Checks the
 * current session for the "userLogged" boolean variable
 *
 * @author Breno Leite
 */
public class AuthenticationFilter implements Filter {

    /**
     * Page which is showed if the filter blocks the access to the target
     * resource.
     */
    private String refusePage;

    public AuthenticationFilter() {
    }
    
    public void init(FilterConfig config) throws ServletException {
        refusePage = config.getInitParameter("refuse-page");
    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpSession session = ((HttpServletRequest) request).getSession();
        Boolean isUserLogged = (Boolean) session.getAttribute("userLogged");
        if (isUserLogged == null || isUserLogged.booleanValue() == false) {
            ((HttpServletResponse) response).sendRedirect(getRefusePage());

        } else {
            chain.doFilter(request, response);
        }
    }
    
    public void destroy() {
    }
    
    public String getRefusePage() {
        return refusePage;
    }
}
